<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>webSocket客户端交互访问mdeo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #output {
            margin-top: 20px;
            font-size: 1.2em;
            color: #333;
        }
    </style>
</head>
<script type="text/javascript">
//webSocket客户端 通过js实现
var wsServer = 'ws://127.0.0.1:9502';	//打开一个websocket
var websocket = new WebSocket(wsServer);	
websocket.onopen = function (evt) {
    console.log("Connected to WebSocket server.");
     websocket.send("data....");	//发送数据
};

//关闭socket时
websocket.onclose = function (evt) {
    console.log("Disconnected");	
};

//接收数据
websocket.onmessage = function (evt) {
	//console.log(evt);
    console.log('Received data from server: ' + evt.data);
    document.getElementById('output').textContent = evt.data;
};

websocket.onerror = function (evt, e) {
    console.log('Error occured: ' + evt.data);
};
</script>
php websocket_server.php
<h2>输入并显示内容</h2>
<input type="text" id="userInput" placeholder="请输入内容...">
<button onclick="handleSubmit()">提交</button>

<div id="output"></div>

<script>
    function handleSubmit() {
        // 获取输入框的值
        const input = document.getElementById('userInput').value;
        // 将内容显示在指定的 div 中
        document.getElementById('output').textContent = '';
        websocket.send(input);	//发送数据
    }
</script>